package com.example.chmextractor;

import org.jchmlib.ChmFile;
import org.jchmlib.ChmUnitInfo;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class CHMExtractor {
    public static void main(String[] args) {
        // if (args.length < 2) {
        //     System.out.println("用法: java CHMExtractor <input.chm> <output.txt>");
        //     return;
        // }
        String chmFilePath = "C:\\Users\\wzh\\zhongyi\\chm\\中医教材\\《中医基础理论》.chm";
        String outputFilePath = "C:\\Users\\wzh\\zhongyi\\chm\\中医教材\\《中医基础理论》.txt";
        
        try {
            extractContent(chmFilePath, outputFilePath);
            System.out.println("提取完成！输出文件：" + outputFilePath);
        } catch (Exception e) {
            System.err.println("处理文件时出错：" + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void extractContent(String chmFilePath, String outputFilePath) throws IOException {
        ChmFile chmFile = new ChmFile(chmFilePath);
        System.out.println("CHM文件编码：" + chmFile.getEncoding());
        System.out.println("CHM文件标题：" + chmFile.getTitle());
        
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                    new FileOutputStream(outputFilePath), 
                    StandardCharsets.UTF_8))) {
            
            List<ChmUnitInfo> htmlFiles = new ArrayList<>();
            
            // 使用enumerate方法遍历所有文件
            chmFile.enumerate(ChmFile.CHM_ENUMERATE_ALL, (ui) -> {
                if (ui.getPath().toLowerCase().endsWith(".htm") || 
                    ui.getPath().toLowerCase().endsWith(".html")) {
                    htmlFiles.add(ui);
                }
            });

            System.out.println("找到 " + htmlFiles.size() + " 个HTML文件");
            
            // 处理每个HTML文件
            for (ChmUnitInfo ui : htmlFiles) {
                try {
                    String content = chmFile.retrieveObjectAsString(ui);
                    if (content != null) {
                        // 使用Jsoup解析HTML并提取文本
                        Document doc = Jsoup.parse(content);
                        String text = doc.text();
                        
                        // 获取文件的标题（如果有的话）
                        String title = chmFile.getTitleOfObject(ui.getPath());
                        
                        // 写入文件名和标题
                        writer.write("=== " + ui.getPath() + " ===\n");
                        if (!ui.getPath().equals(title)) {
                            writer.write("标题: " + title + "\n");
                        }
                        writer.write(text);
                        writer.write("\n\n");
                        
                        System.out.println("已处理: " + ui.getPath());
                    }
                } catch (Exception e) {
                    System.err.println("处理文件 " + ui.getPath() + " 时出错: " + e.getMessage());
                }
            }
        }
    }
}
